extends StaticBody2D

export(NodePath) var player_path

var view_direction = Vector2.DOWN # 视野正方向（眼睛的位置）
var view_angle_range = deg2rad(90) # 视野的广度 （度数转弧度）
var view_length = 500.0 # 视野的纵深

var view_angle_max # 视野角度上限
var view_angle_min # 视野角度下限


func _ready():
	view_angle_max = view_direction.angle() + view_angle_range/2 
	var max_point = Vector2(view_length,0).rotated(view_angle_max)
	$maxLab.text = str(round(rad2deg(view_angle_max))) + "°"
	$maxLab.rect_position = max_point
	view_angle_min = view_direction.angle() - view_angle_range/2 
	var min_point = Vector2(view_length,0).rotated(view_angle_min)
	$minLab.text = str(round(rad2deg(view_angle_min))) + "°"
	$minLab.rect_position = min_point
	# 显示视野边线
	$line1.add_point(Vector2.ZERO)
	$line1.add_point(min_point)
	$line2.add_point(Vector2.ZERO)
	$line2.add_point(max_point)
	
	var unit_angle = deg2rad(1) # 用于旋转的最小角度
	var step = round(view_angle_range / unit_angle) # 需要的步数
	$line3.add_point(min_point)
	for i in range(1,step):
		$line3.add_point(min_point.rotated(unit_angle * i))
	$line3.add_point(max_point)
	pass 

func _process(delta):
	var player_node:KinematicBody2D = get_node(player_path)
	var angle = player_node.position.angle_to_point(position)
	if angle < deg2rad(-90):
		angle = angle + deg2rad(360)
	var distance = player_node.position.distance_to(position)
	$"Label2".text = "角度:" + str(round(rad2deg(angle))) + "° 距离:" + str(round(distance))
	if angle > view_angle_min and angle < view_angle_max and distance < view_length:
		$"Label".text = "进入视野内"
	else:
		$"Label".text = "不在视野内"
	pass
